import { CheckOutlined, ClockCircleOutlined, StopOutlined } from '@ant-design/icons'
import { Spin, message, Tooltip } from 'antd'
import { Modal, Empty } from '@/desktop/components'
import services from '@/services'
import { ChatFlowApplyStatus, formatChatFlowTaskTime } from '@/services/features/chat-flows'
import type { ChatFlowApplyRecord, Word } from '@/services/features/chat-flows'
import PreviewWords from './PreviewWords'
import './ApplyRecords.module.less'

export default function Records(props: { contactId: string | null; onClose: () => void }) {
  const { contactId, onClose } = props

  return <Modal
    open={contactId !== null}
    onCancel={onClose}
    title="查看执行情况"
    width="600px"
    footer={null}
    styleName="modal"
  >
    {contactId !== null ? <Content contactId={contactId} /> : null}
  </Modal>
}

function Content(props: { contactId: string }) {
  const { contactId } = props

  const [records, setRecords] = useState<ChatFlowApplyRecord[] | null>(null)

  const load = useCallback(async () => {
    const res = await services.features.chatFlows.getApplyRecords(contactId)
    if (res.success) setRecords(res.data)
    else void message.error(`执行记录加载失败：${res.error}`)
  }, [contactId])
  useEffect(() => void load(), [load])

  const [previewingWords, setPreviewingWords] = useState<Word[] | null>(null)

  // ===========================================================

  const loading = <div styleName="loading">
    <Spin tip="加载中..." size="large" />
  </div>

  const empty = <div styleName="empty">
    <Empty description="没有发送记录" />
  </div>

  if (!records) return loading
  if (!records.length) return empty

  return <>
    {records.map((record, index) => <div key={index} styleName="record">
      <div styleName="info-row">
        第{record.day}日<span>{formatChatFlowTaskTime(record)}</span>发送
      </div>

      {record.status === ChatFlowApplyStatus.Idle ? (
        <div styleName="status-row">
          <ClockCircleOutlined styleName="idle" />
          <Tooltip title={record.sendTime}>
            <div styleName="desc">待执行</div>
          </Tooltip>
          <a onClick={() => setPreviewingWords(record.words)}>查看待发送内容</a>
        </div>
      ) : null}

      {record.status === ChatFlowApplyStatus.Applied ? (
        <div styleName="status-row">
          <CheckOutlined styleName="applied" />
          <div styleName="desc">于 {record.sendTime} 执行</div>
          <a onClick={() => setPreviewingWords(record.words)}>查看发送内容</a>
        </div>
      ) : null}

      {record.status === ChatFlowApplyStatus.Unsubscribed ? (
        <div styleName="status-row">
          <StopOutlined styleName="unsubscribed" />
          <div styleName="desc">用户发送退出关键字终止</div>
        </div>
      ) : null}
    </div>)}

    <PreviewWords words={previewingWords} onClose={() => setPreviewingWords(null)} />
  </>
}
